package com.library.service;

import com.library.model.Reader;
import com.library.repository.ReaderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class ReaderService {
    private final ReaderRepository readerRepository;

    @Autowired
    public ReaderService(ReaderRepository readerRepository) {
        this.readerRepository = readerRepository;
    }

    public List<Reader> getAllReaders() {
        return readerRepository.findAll();
    }

    public Optional<Reader> getReaderById(Long id) {
        return readerRepository.findById(id);
    }

    public List<Reader> getReadersByName(String name) {
        return readerRepository.findByNameContainingIgnoreCase(name);
    }

    public Reader addReader(Reader reader) {

        reader.setRegistrationDate(LocalDate.now().toString());
        return readerRepository.save(reader);
    }

    public Reader updateReader(Long id, Reader readerDetails) {
        return readerRepository.findById(id)
                .map(reader -> {
                    reader.setName(readerDetails.getName());
                    reader.setEmail(readerDetails.getEmail());
                    reader.setPhone(readerDetails.getPhone());
                    reader.setAddress(readerDetails.getAddress());

                    return readerRepository.save(reader);
                })
                .orElseThrow(() -> new IllegalArgumentException("Reader not found with id: " + id));
    }

    public void deleteReader(Long id) {
        readerRepository.deleteById(id);
    }
}
